package fw.qaz.asmx.reader;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import fw.qaz.asmx.reader.parser.TxtParser;
import fw.qaz.asmx.reader.view.ReadView;
import fw.qaz.asmx.reader.utils.Convertor;

public class FloatingWindowService extends Service implements
        GestureDetector.OnGestureListener
{
    @Nullable @Override public IBinder onBind(Intent intent)
    {
        return null;
    }

    private int w;
    private int h;

    @Override public void onCreate()
    {
        super.onCreate();
        rvf = new ReadView(getApplicationContext());
        w = Convertor.dp2px(this, 230);
        h = Convertor.dp2px(this, 350);
        pagefactory = new TxtParser(rvf, SettingCenter.getFontSize(this),
                                          SettingCenter.getFontColor(this),
                                          SettingCenter.getBackgroundColor(this));
        //
        gesturer = new GestureDetectorCompat(this, this);
        //
    }

    private String book;

    @Override public int onStartCommand(Intent intent, int flags, int startId)
    {
        String path = intent.getStringExtra("Path");
        book = path;
        int pos = intent.getIntExtra("Progress", 0);
        pagefactory.openBook(path);
        pagefactory.setBeginPos(pos);
        //
        createFloatView();
        return START_NOT_STICKY;
    }

    private TxtParser pagefactory;

    //Test
    private ReadView rvf;
    private boolean isAdded = false; // 是否已增加悬浮窗

    private static WindowManager wm;
    private static WindowManager.LayoutParams params;
    //
    private Bitmap curPageBitmapFlt;
    private Canvas curPageCanvasFlt;

    //
    private GestureDetectorCompat gesturer;

    public void createFloatView()
    {
        wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();

        // 设置window type
        //params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        params.type = WindowManager.LayoutParams.TYPE_PHONE;

        params.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明

        // 设置Window flag
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                       | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

//        params.flags=WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
//                       | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                       | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        // 设置悬浮窗的长宽
        params.width = w;
        params.height = h;
        //
        wm.addView(rvf, params);
        //
        curPageBitmapFlt =
                Bitmap.createBitmap(params.width, params.height, Bitmap.Config.ARGB_4444);//当前页位图
        curPageCanvasFlt = new Canvas(curPageBitmapFlt);//显示当前页位图
        //
        pagefactory.setWidthAndHeight(params.width, params.height);
        //
        pagefactory.freshUI();
        rvf.setBitmaps(curPageBitmapFlt);
        rvf.postInvalidate();
        //
        rvf.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent e)
            {
                return gesturer.onTouchEvent(e);
            }
        });
        //
        rvf.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                int lastY = (Integer) v.getTag();
                if (lastY < v.getWidth() / 3)
                {
                    pagefactory.prevPage();
                    if (pagefactory.isfirstPage())
                    {
                        Toast.makeText(FloatingWindowService.this, R.string.first_page,
                                       Toast.LENGTH_SHORT).show();
                        return;
                    }
                    pagefactory.freshUI();
                }
                else if (lastY > v.getWidth() / 3 * 2)
                {
                    pagefactory.nextPage();
                    if (pagefactory.islastPage())
                    {
                        Toast.makeText(FloatingWindowService.this, R.string.end_page,
                                       Toast.LENGTH_SHORT).show();
                        return;
                    }
                    pagefactory.freshUI();
                }
                else
                {
                    //settings
                }
            }
        });
        //
        rvf.setOnTouchListener(new View.OnTouchListener()
        {
            int lastX, lastY;
            int paramX, paramY;

            public boolean onTouch(View v, MotionEvent event)
            {
                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        if (Math.abs(dx) > 5 || Math.abs(dy) > 5)
                        {
                            params.x = paramX + dx;
                            params.y = paramY + dy;
                            // 更新悬浮窗位置
                            wm.updateViewLayout(rvf, params);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        int dlx = (int) event.getRawX() - lastX;
                        int dly = (int) event.getRawY() - lastY;
                        if (Math.abs(dlx) <= 5 && Math.abs(dly) <= 5)
                        {
                            v.setTag(lastY);
                        }
                        break;
                }
                return true;
            }
        });
        isAdded = true;
    }

    @Override public void onDestroy()
    {
        SettingCenter.saveBookmark(
                this, book, 1, pagefactory.getCommit(),
                pagefactory.getCurProgress());
        wm.removeView(rvf);
        super.onDestroy();
    }

    private boolean isLongTap = false;

    @Override public boolean onDown(MotionEvent e)
    {
        return false;
    }

    @Override public void onShowPress(MotionEvent e)
    {

    }

    @Override public boolean onSingleTapUp(MotionEvent e)
    {
        if (isLongTap)
        {
            isLongTap = false;
            Toast.makeText(this,"LongTap",Toast.LENGTH_SHORT).show();
            return false;
        }
        else
        {
            Toast.makeText(this,"NotLongTap",Toast.LENGTH_SHORT).show();
            if (e.getX() < rvf.getWidth() / 3)
            {
                pagefactory.prevPage();
                if (pagefactory.isfirstPage())
                {
                    Toast.makeText(this, R.string.first_page, Toast.LENGTH_SHORT)
                         .show();
                    return true;
                }
                pagefactory.freshUI();
            }
            else if (e.getX() > rvf.getWidth() / 3 * 2)
            {
                pagefactory.nextPage();
                if (pagefactory.islastPage())
                {
                    Toast.makeText(this, R.string.end_page, Toast.LENGTH_SHORT)
                         .show();
                    return true;
                }
                pagefactory.freshUI();
            }
            else
            {
                //settings
            }
            rvf.postInvalidate();
            return false;
        }
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    @Override public void onLongPress(MotionEvent e)
    {
        isLongTap = true;
        rvf.performLongClick();
        Toast.makeText(this,"LongPress",Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        return false;
    }
}
